package cn.itcast.erp.controller;

import cn.itcast.erp.dao.mapper.MenuMapper;
import cn.itcast.erp.entity.Emp;
import cn.itcast.erp.entity.Menu;
import cn.itcast.erp.entity.utils.ResultAjax;
import cn.itcast.erp.service.EmpService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/***
 * 登录模块Controller
 * @author wjy
 */
@RestController
public class LoginController {

    @Resource
    private MenuMapper mm;

    @Resource
    private EmpService empService;


    /**
     * 登录检查
     * @param emp
     * @param request
     * @return ar
     */
    @RequestMapping("/checkUser")
    public ResultAjax checkEmp(@Validated(Emp.LoginGroup.class) Emp emp, NativeWebRequest request){

        ResultAjax ar = new ResultAjax();
        Emp emp1 = this.empService.findByUsernameAndPwd(emp);
        if (emp1 != null){
            ar.setMessage("登录成功!!");
            ar.setCode(200);
            ar.setObj(emp1);
            request.setAttribute("emp", emp1, RequestAttributes.SCOPE_SESSION);
            return ar;
        }else {
            ar.setMessage("用户名或密码错误!!");
            ar.setCode(100);
            ar.setObj(emp1);
            return ar;
        }
    }

    /**
     * 获取用户名
     * @param emp
     * @return ar 用户名
     */
    @RequestMapping("/showName")
    public ResultAjax showName(@SessionAttribute("emp") Emp emp, NativeWebRequest request){
        ResultAjax ar = new ResultAjax();
        if (emp != null){
            ar.setMessage("用户信息");
            ar.setCode(200);
            ar.setObj(emp.getName());
            List<Menu> userMenuList = mm.getMenu(emp.getUuid());
            request.setAttribute("userMenuList", userMenuList, RequestAttributes.SCOPE_SESSION);
            return ar;
        }else {
            ar.setMessage("用户信息");
            ar.setCode(100);
            ar.setObj(emp.getName());
            return ar;
        }

    }

    @RequestMapping("/loginOut")
    public void loginOut(HttpServletRequest request){

        request.getSession().removeAttribute("emp");

    }


}
